python |
您所在的位置:网站首页 › Python-docx 获取编号 › python |
不幸的是,数字不是文本的一部分,而是由Word自己根据标题样式(Heading i)生成的,我认为docx不会公开任何方式来获取这个数字。 但是,您可以使用para.style检索样式/级别,然后通读文档以重新计算编号方案。然而,这很麻烦,因为它没有考虑到您可以使用的任何自定义样式。也许有一种方法可以访问文档的style.xml部分中的编号方案,但我不知道如何访问。 import docx level_from_style_name = {f'Heading {i}': i for i in range(10)} def format_levels(cur_lev): levs = [str(l) for l in cur_lev if l != 0] return '.'.join(levs) # Customize your format here d = docx.Document('my_doc.docx') current_levels = [0] * 10 full_text = [] for p in d.paragraphs: if p.style.name not in level_from_style_name: full_text.append(p.text) else: level = level_from_style_name[p.style.name] current_levels[level] += 1 for l in range(level + 1, 10): current_levels[l] = 0 full_text.append(format_levels(current_levels) + ' ' + p.text) for l in full_text: print(l)它来自于 ![]() 给了我 Hello world 1 H1 foo 1.1 H2 bar 1.1.1 H3 baz Paragraph are really nice ! 1.1.2 H3 bibou Something else 2 H1 foofoo You got the drill… |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |